package cn.org.rookie.jeesdp.tools.controller;

import cn.org.rookie.jeesdp.core.properties.ConsulProperties;
import cn.org.rookie.jeesdp.core.properties.JeesdpProperties;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Member;
import com.ecwid.consul.v1.agent.model.Service;
import com.ecwid.consul.v1.catalog.CatalogServiceRequest;
import com.ecwid.consul.v1.catalog.model.CatalogService;
import com.ecwid.consul.v1.coordinate.model.Node;
import com.ecwid.consul.v1.health.HealthServicesRequest;
import com.ecwid.consul.v1.health.model.HealthService;
import com.ecwid.consul.v1.kv.model.GetValue;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("consul")
public class ConsulController {

    @Autowired
    private JeesdpProperties properties;
    private ConsulClient client;

    @PostConstruct
    private void init() {
        ConsulProperties consulProperties = properties.getConsul();
        client = new ConsulClient(consulProperties.getHost(), consulProperties.getPort());
    }

    @RequestMapping("demo")
    public String demo() {
        return "demo";
    }

    @RequestMapping("nodes")
    public List<Node> nodes() {
        return client.getNodes(new QueryParams(properties.getConsul().getDataCenter())).getValue();
    }

    @RequestMapping("kvNames")
    public List<String> kvNames() {
        return client.getKVKeysOnly("/").getValue();
    }

    @RequestMapping("kvValue")
    public GetValue kvValue(String key) {
        return client.getKVValue(key).getValue();
    }

    @RequestMapping("updateValue")
    public Boolean kvValue(String key, String value) {
        return client.setKVValue(key, value).getValue();
    }

    @RequestMapping("deleteValue")
    public void deleteValue(String key) {
        client.deleteKVValue(key);
    }

    @RequestMapping("services")
    public List<Member> services() {
        Response<List<Member>> agentMembers = client.getAgentMembers();
        return agentMembers.getValue();
    }

    @RequestMapping("agentServices")
    public Map<String, Service> agentServices() {
        return client.getAgentServices().getValue();
    }

    @RequestMapping("catalogService")
    public List<CatalogService> catalogService(String name) {
        return client.getCatalogService(name, CatalogServiceRequest.newBuilder().build()).getValue();
    }

    @RequestMapping("healthServices")
    public List<HealthService> healthServices(String name) {
        return client.getHealthServices(name, HealthServicesRequest.newBuilder().build()).getValue();
    }
}
